package net.jueb.marshalling.server;

import java.util.HashMap;

import net.jueb.marshalling.ProviderFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.marshalling.MarshallingDecoder;
import io.netty.handler.codec.marshalling.MarshallingEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.AttributeKey;

public class MarshallingServer {
	
	public void start(int port)
	{
		NioEventLoopGroup boss=new NioEventLoopGroup();
		NioEventLoopGroup worker=new NioEventLoopGroup();
		ServerBootstrap sbt=new ServerBootstrap();
		sbt.group(boss, worker);
		AttributeKey<HashMap<Object,Object>> MAPKEY=AttributeKey.valueOf("MAPKEY");
		sbt.attr(MAPKEY, new HashMap<Object,Object>());
		sbt.channel(NioServerSocketChannel.class);
		sbt.handler(new LoggingHandler(LogLevel.INFO));
		sbt.childHandler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel sc) throws Exception {
				//加入解码器 自带半包处理
				sc.pipeline().addLast(new MarshallingDecoder(ProviderFactory.getDecoderProvider("serial", 5)));
				//加入编码器
				sc.pipeline().addLast(new MarshallingEncoder(ProviderFactory.getEncoderProvider("serial", 5)));
				sc.pipeline().addLast(new MarshallingServerHandler());
			}
		});
		
		try {
			ChannelFuture cf = sbt.bind(port).sync();
			cf.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			boss.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}
	public static void main(String[] args) {
		new MarshallingServer().start(80);
	}
}
